<template>
  <div style="height: 100%; width: 100%; position: relative;">
      <div class="pagetop" ref="buttondiv" width="100%">
          <template>
              <table width="100%">
                  <tr>
                      <td width="80px" align="right">仪器</td>
                      <td>
                          <rm-ddl-instrument @change="labinstrumentchange" width="200px" v-model="instrId" defaultflag="1" prgno="LIS515" :clearable="false"></rm-ddl-instrument>
                      </td>

                      <td align="right">
                          <el-button icon="el-icon-search" @click="initialList" v-has="'PINQUERY'">查询(F8)</el-button>
                          <el-button icon="el-icon-edit-outline" @click.shift="BtnAdd()" @click="BtnAdd()" v-has="'PADD'">新增(F2)</el-button>
                          <el-button icon="el-icon-delete-solid" @click="BtnDel()" v-has="'PDELETE'">删除(F3)</el-button>
                          <el-button type="primary" icon="el-icon-success" @click="BtnSave()" v-has="'PMODIFY'">保存(F6)</el-button>
                          <el-button icon="el-icon-close" @click="BtnExc">退出(E)</el-button>
                      </td>
                  </tr>
              </table>
          </template>
      </div>
      <div class="pagecenter">
          <div ref="xTableDiv" style="height: 99%; width: 100%;">
              <vxe-table show-overflow ref="xTable1" height="auto" width="100%" :loading="loading" :select-config="{ reserve: true }" :data.sync="tableData1" border size="mini" :keyboard-config="keyConfig" :mouse-config="{ selected: true }" show-header-overflow highlight-current-row highlight-hover-row resizable stripe :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }">
                  <vxe-table-column type="index" title="NO." width="50"></vxe-table-column>
                  <vxe-table-column field="rpt_itemcode" key="rpt_itemname" title="规则应用对象" width="230px" header-align="center">
                      <template v-slot="{ row }">
                          <rm-ddl-common datatype="instrrptitem" dataname="仪器对应报告项目" v-model="row.rpt_itemcode" :instrid="parseInt(instrId)" width="200px"> </rm-ddl-common>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="seq" title="优先级" width="90" sortable align="center" :edit-render="{ name: 'input' }"></vxe-table-column>
                  <vxe-table-column field="conkind" title="条件" width="180" header-align="center" :edit-render="{ type: 'default' }">
                      <template v-slot="{ row }">
                          <el-select v-model="row.conkind">
                              <el-option v-for="item in conkindOption" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
                          </el-select>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="conparm1" title="条件取值1" :edit-render="{ name: 'input' }" width="100" header-align="center"></vxe-table-column>
                  <vxe-table-column field="transkind" title="处理方式" width="180" header-align="center" :edit-render="{ type: 'default' }">
                      <template v-slot="{ row }">
                          <el-select v-model="row.transkind">
                              <el-option v-for="item in transkindOption" :key="item.value" :label="item.label" :value="item.value">{{ item.label }}</el-option>
                          </el-select>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="transparm1" title="处理取值1" :edit-render="{ name: 'input' }" width="100" header-align="center"></vxe-table-column>
              </vxe-table>
          </div>
      </div>
  </div>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils"; //引入工具类
export default {
  name: "LIS515",
  data() {
      return {
          loading: false,
          instrId: 0,
          tableData1: [],
          keyConfig: {
              isArrow: true,
              isDel: true,
              isTab: true,
              isEdit: true,
              editMethod: ({ seq, row, rowIndex, column, columnIndex, cell }) => {},
          },
          conkindOption: [
              { label: "结果＝", value: "1" },
              { label: "结果>", value: "2" },
              { label: "结果>=", value: "3" },
              { label: "结果<", value: "4" },
              { label: "结果<=", value: "5" },
              { label: "结果包含", value: "6" },
              { label: "结果开头=", value: "7" },
              { label: "结果结尾=", value: "8" },
              { label: "代码(编程人员专用)", value: "Z" },
          ],
          transkindOption: [
              { label: "则结果直接", value: "1" },
              { label: "则包含字符替换为", value: "2" },
              { label: "代码(编程人员专用)", value: "Z" },
          ],
      };
  },

  //html加载完成之前，执行。执行顺序：父组件-子组件
  created() {},
  //.html加载完成后执行。执行顺序：子组件-父组件
  mounted() {},
  updated() {},
  watch: {
      instrId(val) {
          this.initialList();
      },
  },
  methods: {
      //初始化数据
      resetData() {
          this.tableData1 = [];
      },

      initialList() {
          //主表查询
          this.loading = true;
          this.resetData();
          this.$tool
              .request({
                  url: "LIS/LIS5/LIS515",
                  method: "post",
                  data: {
                      action: "query",
                      instrid: this.instrId,
                  },
              })
              .then((response) => {
                  this.tableData1 = response.Data;
                  this.loading = false;
              })
              .catch((e) => {
                  this.loading = false;
              });
      },

      //切换仪器时刷新界面
      labinstrumentchange(id, name) {
          this.instrId = id;
          this.$nextTick(() => {
              this.initialList();
          });
      },

      BtnAdd() {
          var row = {};
          this.insertRowAtLast(this.$refs.xTable1, row);
      },

      BtnSave() {
          if (this.instrId == 0) {
              this.$message("请选择仪器");
              return false;
          }
          //校验 数据
          var record = this.$refs.xTable1.tableData;
          for (let i = 0, len = record.length; i < len; i++) {
              let msg;
              msg = this.valid(record[i].rpt_itemcode, "第" + (i + 1) + "行 规则应用对象 必须填写！");
              if (msg) return msg;
              msg = this.valid(record[i].seq, "第" + (i + 1) + "行 优先级 必须填写！");
              if (msg) return msg;
              msg = this.valid(record[i].transkind, "第" + (i + 1) + "行 处理方式 必须填写！");
              if (msg) return msg;
          }

          for (let i = 0; i < record.length; i++) {
              for (let m = i + 1; m < record.length; m++) {
                  if (record[i].rpt_itemcode == record[m].rpt_itemcode && record[i].seq == record[m].seq) {
                      return this.$message({
                          message: "规则应用对象 + 优先级 不能重复！",
                          type: "warning",
                      });
                  }
              }
          }
          let xTable1data = this.$refs.xTable1.getRecordset();
          let fullData = this.$refs.xTable1.getTableData().fullData;
          this.getDataByAjax(
              {
                  url: "LIS/LIS5/LIS515",
                  method: "post",
                  data: {
                      action: "save",
                      instrId: this.instrId,
                      urec: fullData, // 原来：xTable1data
                  },
              },
              "操作成功！",
              "保存失败！",
              (data) => {
                  //okFunction
                  this.initialList();
              },
              (data) => {
                  //errFunction
              }
          );
      },

      BtnDel() {
          this.deleteRow(this.$refs.xTable1);
      },

      ///////////////////////////////////工具函数 /////////////////////////////////////////
      getDataByAjax(
          request,
          okMsg,
          errMsg,
          okFunction, // 取得数据后的回调函数
          errFunction // 获取数据失败后回调函数
      ) {
          this.$tool.request(request).then((response) => {
              if (response.errcode == "1") {
                  if (XEUtils.isString(okMsg)) {
                      if (XEUtils.getSize(XEUtils.trim(okMsg)) > 0) {
                          this.$message({
                              message: okMsg,
                              type: "success",
                          });
                      }
                  }
                  if (typeof okFunction == "function") okFunction(response.Data);
              } else {
                  this.$message({
                      dangerouslyUseHTMLString: true,
                      message: errMsg + "<br><br>详细信息：" + response.errmsg,
                      type: "warning",
                  });
                  if (typeof errFunction == "function") errFunction(response.Data);
              }
          });
      },

      insertRowAtLast(xtable, row) {
          xtable.insertAt(row, -1); //在最后添加一行
          var curow = xtable.getTableData().fullData[xtable.getTableData().fullData.length - 1]; //获取 新加的行对象 row 数据集合
          xtable.setCurrentRow(curow); //高亮显示行
          this.$nextTick(() => {
              xtable.scrollToRow(curow); //待数据加载完成后，延迟 滚动 到行
          });
      },

      //自动加载表格的第一行，并执行回调函数
      loadFirstRow(xTable, func) {
          this.$nextTick(() => {
              // 加载第一行
              var selectrow = xTable.getData(0);
              if (selectrow) {
                  xTable.setCurrentRow(selectrow); //高亮行
                  xTable.scrollToRow(selectrow); //滚动到行
                  if (typeof func == "function") func(selectrow);
              } else {
                  xTable.setCurrentRow(null); //这个不会自动清空
              }
          });
      },

      //自制必填校验函数，以后待扩展
      valid(obj, message) {
          if (XEUtils.isUndefined(obj)) {
              return this.$message({
                  message: message,
                  type: "warning",
              });
          }
          if (XEUtils.isNull(obj)) {
              return this.$message({
                  message: message,
                  type: "warning",
              });
          }
          if (XEUtils.isString(obj)) {
              if (!XEUtils.getSize(obj) > 0) {
                  return this.$message({
                      message: message,
                      type: "warning",
                  });
              }
          }
          if (XEUtils.isDate(obj)) {
              if (obj < XEUtils.toStringDate("2000-01-01")) {
                  return this.$message({
                      message: message,
                      type: "warning",
                  });
              }
          }
      },

      //删除表格行工具//TODO 连续 点删除按钮会有失去焦点的问题待解决
      deleteRow(xTable) {
          var delrow = xTable.getCurrentRow();
          this.DelIndex = xTable.getRowIndex(delrow);
          xTable.remove(delrow);
          if (this._this.DelIndex > -1 && xTable.tableData.length > 0) {
              if (xTable.getTableData().fullData.length > this.DelIndex) this.DelIndex = this.DelIndex;
              elsethis.DelIndex = this.DelIndex - 1;
              var selectrow = xTable.getTableData().fullData[this._this.DelIndex];
              this.$nextTick(() => {
                  xTable.setCurrentRow(selectrow);
              });
          } else {
              var nowdata = xTable.getTableData().fullData.filter((item) => {
                  return item._XID < delrow._XID;
              });
              if (nowdata.length > 0) {
                  var selectrow = nowdata[nowdata.length - 1];
                  this.$nextTick(() => {
                      xTable.setCurrentRow(selectrow);
                  });
              }
          }
      },

      stddevp(numbers) {
          var mean = 0;
          var sum = 0;
          var avgValue, sdValue, cvValue;
          for (var i = 0; i < numbers.length; i++) {
              sum += Number(numbers[i]);
          }
          mean = sum / numbers.length;
          avgValue = mean;

          sum = 0;
          for (var i = 0; i < numbers.length; i++) {
              sum += Math.pow(numbers[i] - mean, 2);
          }
          sdValue = Math.sqrt(sum / numbers.length);

          if (avgValue != 0) {
              cvValue = (sdValue * 100) / avgValue;
          } else {
              cvValue = null;
          }
          return {
              avgValue: XEUtils.toFixedString(mean, 2),
              sdValue: XEUtils.toFixedString(sdValue, 2),
              cvValue: XEUtils.toFixedString(cvValue, 2),
          };
      },
      //关闭按钮
      BtnExc() {
          let index = this.$parent.$refs.itemtags.tagsList.findIndex((m) => m.name == "LIS515");
          this.$parent.$refs.itemtags.tagsList.splice(index, 1);
          this.$router.go(-1);
      },
  },
  beforeRouteEnter(to, from, next) {
      next((vm) => {
          let that = vm;
          let altArr = [];
          document.onkeydown = function (e) {
              let key = window.event.keyCode;
              console.log("key=", key);
              //*组合按键
              if (altArr.length > 0) {
                  //65到90 a到z（A到Z）
                  // //*Alt + C 清除
                  // if (key == 67) {
                  //     this.BtnExc();
                  // }
                  //*Alt + E 退出
                  if (key == 69) {
                      that.BtnExc();
                  }
              } else {
                  if (key == 119) {
                      //F8
                      that.initialList();
                  } else if (key == 113) {
                      //F2
                      var e = [];
                      e.shiftKey = false;
                      that.BtnAdd(e);
                  } else if (key == 114) {
                      //F3
                      that.BtnDel();
                  } else if (key == 117) {
                      //F6
                      that.BtnSave();
                  } else if (key == 18) {
                      console.log("按下'ALT'");
                      //按下了alt
                      altArr.push(key);
                  }
              }
          };
          document.onkeyup = function (e) {
              let key = window.event.keyCode;
              if (key == 18) {
                  altArr = [];
              }
          };
      });
  },
};
</script>

<style scoped>
.pagetop {
  left: 0;
  right: 0;
  height: 30px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: solid 1px #ccc;
  position: absolute;
  z-index: 99;
  text-align: left;
}
.pagebottom {
  width: 100%;
  height: 40px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: left;
  position: absolute;
  bottom: 0px;
  font-size: 12px;
  border: solid 1px #ccc;
}
.pagecenter {
  position: absolute;
  top: 35px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}
.middle-center {
  position: absolute;
  height: 100%;
  right: 485px;
  left: 0;
}

.middle-right {
  position: absolute;
  top: 0;
  bottom: 2px;
  overflow: visible;
  width: 480px;
  right: 0px;
}
table tr td:nth-child(odd) {
  text-align: right;
  white-space: nowrap;
}
table tr td:nth-child(even) {
  text-align: left;
}

table tr td:nth-child(1) {
  width: 80px;
}
table {
  font-size: 12px;
}
</style>
